/*
 * Copyright (C) 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ohos.ringdroid.core;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.data.resultset.ResultSet;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.util.HashMap;

public class SongMetadataReader {
    public Uri GENRES_URI = AVStorage.Audio.Media.EXTERNAL_DATA_ABILITY_URI;
    public Context mActivity = null;
    public String mFilename = "";
    public String mTitle = "";
    public String mArtist = "";
    public String mAlbum = "";
    public String mGenre = "";
    public int mYear = -1;

    public SongMetadataReader(Context context, String filename) {
        mActivity = context;
        mFilename = filename;
        mTitle = getBasename(filename);
        try {
            ReadMetadata();
        } catch (Exception e) {
        }
    }

    private void ReadMetadata() {
        // Get a map from genre ids to names
        HashMap<String, String> genreIdMap = new HashMap<String, String>();
        DataAbilityHelper helper = DataAbilityHelper.creator(mActivity);

        ResultSet resultSet = null;
        try {
            resultSet = helper.query(GENRES_URI,
                    new String[]{
                            AVStorage.Audio.Genres.ID,
                            AVStorage.Audio.Genres.DISPLAY_NAME},
                    null);
            while (resultSet.goToNextRow()) {
                genreIdMap.put(resultSet.getString(0), resultSet.getString(1));
            }
            resultSet.close();
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

        mGenre = "";
        for (String genreId : genreIdMap.keySet()) {
            try {
                resultSet = helper.query(makeGenreUri(genreId),
                        new String[]{AVStorage.Audio.Media.DATA, AVStorage.Audio.Media.DATA + " LIKE \"" + mFilename
                                + "\""},
                        null);
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            }

            if (resultSet.getRowCount() != 0) {
                mGenre = genreIdMap.get(genreId);
                break;
            }
            resultSet.close();
            resultSet = null;
        }

        Uri uri = AVStorage.Audio.Media.fetchResource(mFilename);
        try {
            resultSet = helper.query(uri,
                    new String[]{
                            AVStorage.Audio.Media.ID,
                            AVStorage.Audio.Media.TITLE,
                            AVStorage.Audio.Media.VOLUME_NAME,
                            AVStorage.Audio.Media.DISPLAY_NAME,
                            AVStorage.Audio.Media.DATE_ADDED,
                            AVStorage.Audio.Media.DATA,
                            AVStorage.Audio.Media.DATA + " LIKE \"" + mFilename + "\""},
                    null);

            if (resultSet.getRowCount() == 0) {
                mTitle = getBasename(mFilename);
                mArtist = "";
                mAlbum = "";
                mYear = -1;
                return;
            }
            resultSet.goToFirstRow();
            mTitle = getStringFromColumn(resultSet, AVStorage.Audio.Media.TITLE);
            if (mTitle == null || mTitle.length() == 0) {
                mTitle = getBasename(mFilename);
            }
            mArtist = getStringFromColumn(resultSet, AVStorage.Audio.Media.VOLUME_NAME);
            mAlbum = getStringFromColumn(resultSet, AVStorage.Audio.Media.DISPLAY_NAME);
            mYear = getIntegerFromColumn(resultSet, AVStorage.Audio.Media.DATE_ADDED);
            resultSet.close();
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

    }

    private Uri makeGenreUri(String genreId) {
        String CONTENTDIR = AVStorage.Audio.Genres.Members.OUTPUT;
        return Uri.parse(
                new StringBuilder()
                        .append(GENRES_URI.toString())
                        .append("/")
                        .append(genreId)
                        .append("/")
                        .append(CONTENTDIR)
                        .toString());
    }

    private String getStringFromColumn(ResultSet c, String columnName) {
        int index = c.getColumnIndexForName(columnName);
        String value = c.getString(index);
        if (value != null && value.length() > 0) {
            return value;
        } else {
            return null;
        }
    }

    private int getIntegerFromColumn(ResultSet c, String columnName) {
        int index = c.getColumnIndexForName(columnName);
        Integer value = c.getInt(index);
        if (value != null) {
            return value;
        } else {
            return -1;
        }
    }

    private String getBasename(String filename) {
        return filename.substring(filename.lastIndexOf('/') + 1,
                filename.lastIndexOf('.'));
    }
}
